using System;
using System.Collections.Generic;

namespace TextMenus
{
	public class MenuInputInfo
	{
        // All HASH_* constants should be prime numbers
        private const int HASH_BASE = 47;
        private const int HASH_MULTIPLIER = 29;

        private TextMenu master;
        private MenuOption option;

		private string input;
		private string[] args;

        /// <summary>
        /// Represents a user's text input
        /// </summary>
        /// <param name="_master">The menu which collected the input from the user</param>
        /// <param name="_option">The option which the user chose</param>
        /// <param name="_input">The user's input</param>
		public MenuInputInfo (TextMenu _master, string _input)
		{
			input = _input;
            master = _master;
            InitializeInstance();
		}

        private void InitializeInstance()
        {
            int selection;

            args = input.Split(' ', '\t');

            selection = int.Parse(args[0]);

            option = master.MatchMenuOption(selection);
        }

        /// <summary>
        // Allows us to ignore excessive whitespaces in input when deciding
        // whether MenuInputInfo options are equal to each other
        /// </summary>
        /// <param name="obj">The object to compare</param>
        /// <returns>True if the objects are equal (ignoring whitespaces in input), false otherwise</returns>
        public override bool Equals(object obj)
        {
            MenuInputInfo other = obj as MenuInputInfo;
            if (other == null)
                return false;

            if (other.master != this.master || !other.Args.Length.Equals(this.Args.Length))
                return false;

            for (int x = 0; x < Args.Length; ++x)
            {
                if (!other.Args[x].Equals(this.Args[x]))
                    return false;
            }

            return true;
        }

        public override int GetHashCode()
        {
            int result = HASH_BASE;

            unchecked
            {

                result *= master.GetHashCode();

                foreach (string w in Args)
                    result += HASH_MULTIPLIER * w.GetHashCode();

            }

            return result;
        }

        public string Input
        {
            get { return input; }
        }

        /// <summary>
        /// Access the input line as an array of space-delimited
        /// words
        /// </summary>
        /// <value>
        /// The arguments.
        /// </value>
        public string[] Args
        {
			get { return args; }
		}

        public MenuOption SelectedOption
        {
            get { return option; }
        }
	}
}

